package com.crm.backend.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.crm.backend.domain.entity.RestBean;
import com.crm.backend.domain.po.Customer;
import com.crm.backend.domain.po.Services;
import com.crm.backend.service.ICustomerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dyy
 * @since 2025-05-29
 */
@RestController
@RequestMapping("/api/v1/customer")
public class CustomerController {

    @Autowired
    private ICustomerService customerService;

    /**
     * 新增客户
     * @param customer 客户信息
     * @return RestBean封装的响应结果
     */
    @PostMapping
    public RestBean<Void> addCustomer(@RequestBody Customer customer) {
        boolean savedCustomer = customerService.save(customer);
        return savedCustomer==true?RestBean.success():RestBean.failure(400,"添加失败");
    }
    /**
     * 修改客户
     * @param id 客户编号
     * @param customer 修改后的客户信息
     * @return RestBean封装的响应结果
     */
    @PutMapping("/{id}")
    public RestBean<Void>  updateCustomer(@PathVariable(value = "id") Integer id, @RequestBody Customer customer) {
        customer.setCusId(id);
        boolean updatedCustomer = customerService.updateById(customer);
        if (updatedCustomer == true) {
            return RestBean.success();
        } else {
            return RestBean.failure(404, "客户未找到");
        }
    }

    /**
     * 删除客户
     * @param id 客户编号
     * @return RestBean封装的响应结果
     */
    @DeleteMapping("/{id}")
    public RestBean<Void>  deleteCustomer(@PathVariable(value = "id") Integer id) {
        boolean deleted = customerService.removeById(id);
        if (deleted) {
            return RestBean.success();
        } else {
            return RestBean.failure(404, "客户未找到");
        }
    }


    @GetMapping("/page")
    public RestBean<IPage<Customer>> getServicesByPage(
            @RequestParam(value = "cusName", required = false) String cusName,
            @RequestParam(value = "page") Integer page,
            @RequestParam(value = "size") Integer size) {
        // 创建分页查询对象
        Page<Customer> pageQuery = new Page<>(page, size);
        // 创建查询条件
        LambdaQueryWrapper<Customer> queryWrapper = new LambdaQueryWrapper<>();
        // 如果状态不为空，则添加状态过滤条件
        if (cusName != null) {
            queryWrapper.eq(Customer::getCusName, cusName);
        }
        // 执行分页查询
        IPage<Customer> customerPage = customerService.page(pageQuery, queryWrapper);
        // 封装分页结果并返回
        return RestBean.success(customerPage);
    }
}